import { create } from 'zustand';
import request from '../utils/request';

const API_BASE_URL = 'http://localhost:3000';

const useAuthStore = create((set) => ({
  user: null,
  isAuthenticated: !!localStorage.getItem('token'),
  token: null,
  lastPath: '/',
  
  setUser: (user) => set({ 
    user: user ? {
      ...user,
      avatar: user.avatar ? `${API_BASE_URL}${user.avatar}` : null
    } : null 
  }),
  setToken: (token) => set({ token, isAuthenticated: true }),
  
  // 获取用户信息
  fetchUserInfo: async () => {
    try {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const teacherId = userInfo.id; // 从存储的用户信息中获取 ID
      if (!teacherId) return;

      const res = await request.get(`/api/teacher/profile/${teacherId}`);
      if (res.code === 0) {
        const timestamp = Date.now();
        set({ 
          user: {
            ...res.data,
            avatarTimestamp: timestamp
          }
        });
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  },

  // 更新用户信息
  updateUserInfo: async (teacherId, data) => {
    try {
      const res = await request.put(`/api/teacher/profile/${teacherId}`, data);
      if (res.code === 0) {
        const timestamp = Date.now();
        const updatedUser = {
          ...res.data,
          avatarTimestamp: timestamp
        };
        set({ user: updatedUser });
        return updatedUser;
      }
    } catch (error) {
      console.error('更新用户信息失败:', error);
      throw error;
    }
  },

  // 清除用户信息
  clearUser: () => set({ user: null }),

  // 登录
  login: async (credentials) => {
    try {
      const res = await request.post('/api/teacher/login', credentials);
      if (res.code === 0) {
        const userData = {
          ...res.data.user,
          avatarTimestamp: Date.now()
        };
        // 存储完整的用户信息
        localStorage.setItem('userInfo', JSON.stringify(userData));
        set({ 
          user: userData,
          isAuthenticated: true 
        });
      }
      return res;
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  },

  // 登出
  logout: async () => {
    try {
      const currentPath = window.location.pathname;
      set({ 
        user: null, 
        isAuthenticated: false 
      });
      localStorage.removeItem('userInfo');
      await request.post('/api/teacher/logout');
      // 添加 callback 参数
      window.location.href = `/login?callback=${encodeURIComponent(currentPath)}`;
    } catch (error) {
      console.error('登出失败:', error);
    }
  },

  // 获取上次访问路径
  getLastPath: () => {
    const lastPath = localStorage.getItem('lastPath') || '/';
    localStorage.removeItem('lastPath'); // 使用后清除
    return lastPath;
  },

  // 初始化状态（在应用启动时调用）
  initAuth: () => {
    try {
      const userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        const userData = JSON.parse(userInfo);
        set({
          user: userData,
          isAuthenticated: true
        });
      }
    } catch (error) {
      console.error('初始化认证状态失败:', error);
      localStorage.removeItem('userInfo');
    }
  }
}));

export default useAuthStore; 